//
//  CollectionLinkageViewController.swift
//  SwiftTest
//
//  Created by appleTwo on 2019/5/24.
//  Copyright © 2019 QiKai. All rights reserved.
//

import UIKit

class CollectionLinkageViewController: UIViewController {

    var collectionTopView:UICollectionView!
    var topView:UIView!
 
    
    var heightTopView:CGFloat = 500
    var heightCenter:CGFloat = 40
    var offsetY:CGFloat!{
        get{
           return heightTopView + heightCenter
        }
    }
    var arrdata:[Int] = [1,2,3,4,5,6,7]
    var arrCollection:[UICollectionView] = []//所有collectionview
    var currentCollectionView:UICollectionView?//当前滑动的collectionview
    var currentcontentOffset:CGFloat!//当前滑动的y偏移量
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.creatUI();
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(true)
    }
    private func creatUI(){
        self.currentcontentOffset = -offsetY//默认
        
        topView = UIView.init()
        topView.backgroundColor = UIColor.red
        topView.contentMode = .scaleAspectFill
        self.view.addSubview(topView)
        topView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(heightTopView)
        }
        let lab = UILabel.init()
        lab.text = "测试滑动"
        lab.font = UIFont.systemFont(ofSize: 18)
        topView.addSubview(lab)
        lab.snp.makeConstraints { (make) in
            make.top.equalTo(100)
            make.centerX.equalToSuperview()
            make.height.equalTo(20)
        }
        
        
        let layout = UICollectionViewFlowLayout.init()
        layout.itemSize = CGSize(width: 100, height: 40)//cell高度不能比collectionView高度高
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        layout.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
        collectionTopView = UICollectionView.init(frame: CGRect.null, collectionViewLayout: layout)
        collectionTopView.backgroundColor = .green
        self.view.addSubview(collectionTopView)
        collectionTopView.register(CollectionViewCellTest.self, forCellWithReuseIdentifier: "collectionTopView")
        collectionTopView.delegate = self
        collectionTopView.dataSource = self
        collectionTopView.snp.makeConstraints { (make) in
            make.top.equalTo(topView.snp.bottom)
            make.centerX.equalToSuperview()
            make.width.equalTo(KscreenWidth)
            make.height.equalTo(50)
        }
        
        self.creatCollection()

       
      
    }
    ///创建多个collection
    private func creatCollection(){
        if self.arrdata.count == 0 {
            return
        }
        for _ in 0..<self.arrdata.count {
            let layout2 = UICollectionViewFlowLayout.init()
            layout2.itemSize = CGSize(width: KscreenWidth, height: 60)
            layout2.minimumLineSpacing = 5
            layout2.minimumInteritemSpacing = 5
            layout2.scrollDirection = .vertical
            layout2.sectionInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0)
            let collectionDowmView = UICollectionView.init(frame: CGRect.null, collectionViewLayout: layout2)
            collectionDowmView.backgroundColor = .yellow
            collectionDowmView.bounces = false
            collectionDowmView.isPagingEnabled = true
            self.view.addSubview(collectionDowmView)
            collectionDowmView.register(CollectionViewCellTest.self, forCellWithReuseIdentifier: "collectionDowmView")
            collectionDowmView.delegate = self
            collectionDowmView.dataSource = self
            collectionDowmView.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
            if #available(iOS 11.0, *) {
                UIScrollView.appearance().contentInsetAdjustmentBehavior = UIScrollView.ContentInsetAdjustmentBehavior.never
            } else {
                self.automaticallyAdjustsScrollViewInsets = false
            }
            collectionDowmView.contentInset = UIEdgeInsets.init(top: offsetY, left: 0, bottom: 0, right: 0)
            self.view.sendSubviewToBack(collectionDowmView)
            self.arrCollection.append(collectionDowmView)
        }
        currentCollectionView = self.arrCollection[0]
        self.arrCollection.forEach { (collectionview) in
            collectionview.contentOffset = CGPoint(x: 0, y: -offsetY)
        }
    }
    ///刷新页面 更新试图
    private func collectionreloadData(current:Int){
        if current < self.arrCollection.count {
            
            for (index,value) in self.arrCollection.enumerated(){
                value.isHidden = true
                if index == current{
                    let collectionView = self.arrCollection[current]
                    collectionView.isHidden = false
                    self.currentCollectionView = collectionView
                    
                    if  self.currentcontentOffset != -offsetY,collectionView.contentOffset.y == -offsetY{
                        collectionView.setContentOffset(CGPoint.init(x: 0, y: self.currentcontentOffset), animated: false)
                    }
                    if self.currentcontentOffset > collectionView.contentOffset.y{
                        collectionView.setContentOffset(CGPoint.init(x: 0, y: self.currentcontentOffset), animated: false)
                    }
                    collectionView.reloadData()
                }
                
            }
        }
        
    }
    

}

extension CollectionLinkageViewController:UICollectionViewDelegate,UICollectionViewDataSource{
    //MARK: - UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if collectionView == collectionTopView {
            return arrdata.count
        }
        return 20
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if collectionView == collectionTopView {
            let cell:CollectionViewCellTest = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionTopView", for: indexPath) as! CollectionViewCellTest
            cell.data = indexPath.row
            return cell
        }else{
            let cell:CollectionViewCellTest = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionDowmView", for: indexPath) as! CollectionViewCellTest
            cell.data = indexPath.row
            return cell
        }
       
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionView == collectionTopView {
            collectionView.scrollToItem(at: indexPath, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true)
            if indexPath.row < self.arrCollection.count{
                 self.collectionreloadData(current: indexPath.row)
            }
           
        }
    }

}

extension CollectionLinkageViewController{
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
        
        if scrollView != currentCollectionView {
            return
        }
        //print(scrollView.contentOffset.y)
        let currentoffsety = scrollView.contentOffset.y
        self.currentcontentOffset = currentoffsety
        var delta = currentoffsety + self.offsetY
      
        if delta > heightTopView {
            delta = heightTopView
        }
        self.topView.snp.updateConstraints { (make) in
            make.top.equalTo(-delta)
        }
      
        
    }
    
}



